import java.io.*;
import java.net.*;
import java.util.*;

public class ServerItem {
    public static void main(String args[]) {
        try (ServerSocket server = new ServerSocket(4311)) {
            System.out.println("服务器启动，监听端口 4311");
            while (true) {
                try {
                    System.out.println("等待客户端连接...");
                    Socket client = server.accept();
                    System.out.println("客户端地址: " + client.getInetAddress());
                    new ServerThread(client).start();
                } catch (IOException e) {
                    System.err.println("客户端连接异常: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        }
    }
}

class ServerThread extends Thread {
    private final Socket socket;
    private DataInputStream in;
    private DataOutputStream out;

    public ServerThread(Socket socket) throws IOException {
        this.socket = socket;
        this.out = new DataOutputStream(socket.getOutputStream());
        this.in = new DataInputStream(socket.getInputStream());
    }

    public void run() {
        try (Scanner scanner = new Scanner(in)) {
            String item = in.readUTF();
            System.out.println("收到请求: " + item);

            if (item.startsWith("账单")) {
                double sum = 0;
                Scanner numScanner = new Scanner(item);
                numScanner.useDelimiter("[^\\d.]+");

                while (numScanner.hasNext()) {
                    try {
                        double price = numScanner.nextDouble();
                        sum += price;
                        System.out.println("解析金额: " + price);
                    } catch (NoSuchElementException ignored) {
                    }
                }

                out.writeUTF("您的账单: " + item);
                out.writeUTF("总额: " + sum + "元");
                System.out.println("返回总额: " + sum);
            }
        } catch (Exception e) {
            System.err.println("处理异常: " + e.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                System.err.println("关闭套接字失败: " + e.getMessage());
            }
        }
    }
}